package com.maxtech.common;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.google.android.maps.GeoPoint;
import com.maxtech.basestation.LocationUtil;
import com.maxtech.common.gps.AppConfig;
import com.maxtech.common.gps.GpsTask;
import com.maxtech.common.gps.GpsTaskCallBack;
import com.maxtech.common.gps.LogUtil;
import com.maxtech.common.gps.GpsTask.GpsData;
import com.maxtech.common.gps.IAddressTask.MLocation;
import com.maxtech.common.gps.Utils;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnKeyListener;
import android.location.Location;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MyActivity extends Activity implements OnClickListener {

	private static final int GET_LOCATION = 0;
	private static final int GET_CITY_NAME = 1;
	private static final int ERROR = 2;
	private static final int ERROR_TIME_OUT = 3;

	protected static final int GET_LOCATION_BY_APN = 101;
	protected static final int ERROR_APN = 102;
	protected static final int ERROR_APN_TIMEOUT = 103;
	
	protected static final int GET_LOCATION_BY_GPS = 201;	
	protected static final int ERROR_GPS = 202;
	protected static final int ERROR_GPS_TIMEOUT = 203;

	private static final long GPS_TIMEOUT = AppConfig.GPS_TIME_OUT;
	protected static final String TAG = "GpsActivity";
	private static final int TIME_OUT = AppConfig.TIME_OUT;
	private TextView tx = null;
//	private AlertDialog dialog = null;

	boolean isGPSTaskRunning = false;
	boolean isAPNTaskRunning = false;
	boolean isAPNSuccess = false;
	boolean isGPSSuccess = false;
	boolean isAPNError = false;
	boolean isGPSError = false;
	
//	boolean isGPSTaskFinished = false;
//	boolean isAPNTaskFinished = false;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		
		tx = (TextView) findViewById(R.id.gps_tip);
		findViewById(R.id.do_gps).setOnClickListener(MyActivity.this);
		findViewById(R.id.do_apn).setOnClickListener(MyActivity.this);
		findViewById(R.id.do_wifi).setOnClickListener(MyActivity.this);

//		dialog = new ProgressDialog(MyActivity.this);
//		dialog.setTitle("请稍等...");
//		dialog.setMessage("正在定位...");		
	}
	String log = "";
	@Override
	public void onClick(View v) {		
//		Utils.Toast(this, "不支持GPS功能");
		log = "";
		tx.setText(log);
//		gps_tip.setText("");
//		switch (v.getId()) {
//		case R.id.do_apn:
////			do_apn();
//			getLocationByAPN();
//			break;
//		case R.id.do_gps:
//			doGPS();
//			break;
//		case R.id.do_wifi:
//			do_wifi();
//			break;
//		}
		
		showProgressDialog(MyActivity.this, "请稍候", "正在定位,请稍候", TIME_OUT);

		getLocationByAPN();
		if(isGPSSupported(this)){
			if(isGPSOpened(this)) {
//				Utils.Toast(this, "GPS功能已开启");
				
				log += "\nGPS功能已开启";
				tx.setText(log);
				
				getLocationByGPS();	
			}		
			else {
				log += "\n如需精确定位,请开启GPS功能";
				tx.setText(log);
				
				Utils.Toast(this, "如需精确定位,请开启GPS功能");
			}
			return;
		}
	}

	@Override
	protected void onDestroy() {
		android.os.Process.killProcess(android.os.Process.myPid());
		super.onDestroy();
	}

	private void getLocationByGPS() {
		isGPSTaskRunning = true;
		GpsTask gpstask = new GpsTask(
				MyActivity.this,
				new GpsTaskCallBack() {

					@Override
					public void gpsConnectedTimeOut() {
//						gps_tip.setText("获取GPS超时了");

						handler.sendMessage(Message.obtain(handler, ERROR_GPS_TIMEOUT , "定位失败"));
					}

					@Override
					public void gpsConnected(GpsData gpsdata) {
						if(gpsdata==null){

							handler.sendMessage(Message.obtain(handler, ERROR_GPS , "定位失败"));	
							return;
						}
//						do_gps(gpsdata);

						String result = "getLatLonByGPS"+"location.getLatitude():" + gpsdata.getLatitude() 
								+ ",location.getLongitude():" + gpsdata.getLongitude();
//						
//						GeoPoint tmp = getPoint(gpsdata.getLatitude(), gpsdata.getLongitude());
//						handler.sendMessage(Message.obtain(handler, GET_LOCATION_BY_GPS , tmp));

						handler.sendMessage(Message.obtain(handler, GET_LOCATION_BY_GPS , new double[]{
								gpsdata.getLatitude(), gpsdata.getLongitude()
						}));
						Log.e(TAG, result);
						Utils.Toast(MyActivity.this, result);	
					}
				}, 
				GPS_TIMEOUT);
		gpstask.execute();
	}
	protected void getLocationByAPN() {
		isAPNTaskRunning = true;
		LocationUtil locationutil = new LocationUtil(MyActivity.this);		
		locationutil.setOnGetLocationListener(new LocationUtil.GetLocationListener(){
			@Override
			public void OnGetLocationListener(Location location) {
				if(location==null) {
					handler.sendMessage(Message.obtain(handler, ERROR_APN , "定位失败"));
					return;
				}
//				GeoPoint tmp = getPoint(location.getLatitude(), location.getLongitude());
//				Log.e(TAG, "location.getLatitude():" + location.getLatitude() 
//						+ ",location.getLongitude():" + location.getLongitude());
//				
//				handler.sendMessage(Message.obtain(handler, GET_LOCATION_BY_APN , tmp));
				handler.sendMessage(Message.obtain(handler, GET_LOCATION_BY_APN , new double[]{location.getLatitude(), location.getLongitude()}));
				return;
			}

			@Override
			public void OnGetCityNameListener(String cityname) {				
				handler.sendMessage(Message.obtain(handler, GET_CITY_NAME, cityname));
				return;
			}

			@Override
			public void OnTimeOutListener() {
				handler.sendMessage(Message.obtain(handler, ERROR_APN_TIMEOUT , "定位失败"));
				return;
			}				
		});
		
		locationutil.getLocationByMobile();		
	}
	public boolean hasGPSDevice(Context context)
    {
    	final LocationManager mgr = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
    	if ( mgr == null ) 
    		return false;
    	final List<String> providers = mgr.getAllProviders();
    	if ( providers == null ) 
    		return false;
    	return providers.contains(LocationManager.GPS_PROVIDER);
    }
    private static boolean isGPSSupported(Context context) {
    	LocationManager locationManager = (LocationManager) context  
                .getSystemService(Context.LOCATION_SERVICE);

        boolean isGPSenable = locationManager
        		.isProviderEnabled(LocationManager.GPS_PROVIDER);

        boolean isAGPSenable = locationManager
        		.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        if (!isGPSenable && !isAGPSenable) {  
//        	Toast.makeText(context, "GPS模块支持", Toast.LENGTH_SHORT).show();  
        	return false;
        } 
        else {
//        	Toast.makeText(context, "GPS模块不支持", Toast.LENGTH_SHORT).show();  
        	return true;
        }
	}

	private boolean isGPSOpened(Context context) {  
        LocationManager alm = (LocationManager) context  
                .getSystemService(Context.LOCATION_SERVICE);  
        
        if (alm.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER))            
            return true;  
       
        return false; 
    }
	private void openGPSSettings() {  
        LocationManager alm = (LocationManager) this  
                .getSystemService(Context.LOCATION_SERVICE);  
        if (alm  
                .isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)) {  
            Toast.makeText(this, "GPS模块正常", Toast.LENGTH_SHORT)  
                    .show();
            return;  
        }  
  
        Toast.makeText(this, "请开启GPS！", Toast.LENGTH_SHORT).show();  
        Intent intent = new Intent(Settings.ACTION_SECURITY_SETTINGS);  
        startActivityForResult(intent,0); //此为设置完成后返回到获取界面 
    }
	public static GeoPoint getPoint(double lat, double lon) {
		try{
			return(new GeoPoint((int)(lat*1E6),
		                        (int)(lon*1E6)));
		} 
		catch (Exception e) {
			  return null;  
		}  
	}

	private EHandler handler = new EHandler();
	public class EHandler extends Handler{

		@Override
		public void handleMessage(Message msg) {
			switch(msg.what){
			case GET_LOCATION_BY_APN:
				LogUtil.e(TAG, "GET_LOCATION_BY_APN");

				log += "\nAPN定位成功";
				tx.setText(log);
				
				isAPNTaskRunning = false;
				if(isGPSSuccess)
					return;

				if(!isGPSSupported(getApplicationContext()) || !isGPSTaskRunning || isGPSError) {
					closeProgressDialog();	

					log += "\nGPS模块不支持 / GPS定位失败 / GPS任务停止";
					tx.setText(log);
					
					if(msg.obj==null)
						return;
					
					double[] strz = (double[])msg.obj;
					LogUtil.e(TAG, "APN return success and ignore gps result:" + strz.toString());

					log += "\nAPN成功,GPS失败,转向APN定位结果";
					tx.setText(log);
					
					//	TODO:	goto Map
					return;
				}

				closeProgressDialog();
				LogUtil.e(TAG, "APN return success and waiting for gps result");
				
				if(msg.obj==null)
					return;

				log += "\nAPN成功,转向APN定位结果,等待GPS定位";
				tx.setText(log);
				
				//	TODO:	goto Map
				//	and wait for GPS result
				isAPNSuccess = true;
				double[] strz = (double[])msg.obj;
				LogUtil.e(TAG, strz.toString());
				
				
//				try{
//					ptToSet = (GeoPoint)msg.obj;
//					showMap(ptToSet);
//				} catch(Exception e){
//					LogUtil.ex(TAG, "", e);
//				}				
				break;
			case ERROR_APN_TIMEOUT:
				LogUtil.e(TAG, "ERROR_APN_TIMEOUT");

				log += "\nAPN定位超时";
				tx.setText(log);
				
				isAPNError = true;
				isAPNTaskRunning = false;
				if(!isGPSSupported(getApplicationContext()) || !isGPSTaskRunning || isGPSError) {
					closeProgressDialog();
					log += "\nAPN失败,GPS模块不支持 / GPS定位失败 / GPS任务停止";
					tx.setText(log);
					
					Utils.Toast(getApplicationContext(), "定位失败,请重试");
					return;
				}
				Utils.Toast(getApplicationContext(), "模糊定位失败,正在精确定位中...");
				break;

			case ERROR_APN:
				LogUtil.e(TAG, "ERROR_APN");

				log += "\nAPN定位失败";
				tx.setText(log);

				isAPNError = true;
				isAPNTaskRunning = false;
				if(!isGPSSupported(getApplicationContext()) || !isGPSTaskRunning || isGPSError) {
					closeProgressDialog();
					log += "\nAPN超时, GPS模块不支持 / GPS定位失败 / GPS任务停止";
					tx.setText(log);
					
					Utils.Toast(getApplicationContext(), "定位失败,请重试");
					return;
				}
				Utils.Toast(getApplicationContext(), "模糊定位失败,正在精确定位中...");				
				break;
				
			case GET_LOCATION_BY_GPS:

				log += "\nGPS定位成功";
				tx.setText(log);
				
				isGPSTaskRunning = false;
				
				strz = (double[])msg.obj;				
				if(strz!=null) {
					isGPSSuccess = true;
					closeProgressDialog();	
					if(isAPNSuccess){					
						//	TODO:	show confirm dialog, 
						//	goto gps success
						//	show map	

						log += "\nGPS成功, APN已成功, 显示确认对话框, 是否转向GPS定位结果";
						tx.setText(log);
						
						return;
					} 
					else {
						//	TODO:	goto gps map
						log += "\nAPN失败, GPS成功,转向GPS定位结果";
						tx.setText(log);						
					}
				}
				else {
					if(isAPNSuccess){
						log += "\nGPS结果为空, APN成功,转向APN定位结果";
						tx.setText(log);	
						
						closeProgressDialog();
						//	TODO:	goto apn success, show map					
						return;
					}
					else if(isAPNTaskRunning){
						log += "\nGPS结果为空, 等待APN定位结果";
						tx.setText(log);	
						
						Utils.Toast(getApplicationContext(), "GPS结果为空,等待APN定位结果");
						return;
					}else {
						log += "\nGPS结果为空, APN失败";
						tx.setText(log);	
						
						Utils.Toast(getApplicationContext(), "定位失败,请重试");
						return;
					}
				}
				LogUtil.e(TAG, "GET_LOCATION_BY_GPS:" + strz.toString());

//				if(msg.obj==null){				
//					return;
//				}
//				try{
//					ptToSet = (GeoPoint)msg.obj;
//					showMap(ptToSet);
//				} catch(Exception e){
//					LogUtil.ex(TAG, "", e);
//				}				
				break;
			case ERROR_GPS:
				LogUtil.e(TAG, "ERROR_GPS");

				log += "\nGPS定位失败";
				tx.setText(log);
				
				isGPSTaskRunning = false;
				isGPSError = true;
				
				if(isAPNSuccess){
					closeProgressDialog();
					log += "\nGPS定位失败,APN成功, 转向APN定位结果";
					tx.setText(log);
					
					//	TODO:	goto apn success, show map
					return;
				} 
				else if(isAPNError) {
					closeProgressDialog();
					log += "\nGPS定位失败,APN失败, 显示定位失败";
					tx.setText(log);
					
					Utils.Toast(getApplicationContext(), "定位失败,请重试");
					return;
				}	
				break;
				
			case ERROR_GPS_TIMEOUT:
				LogUtil.e(TAG, "ERROR_GPS_TIMEOUT");

				log += "\n获取GPS超时了";
				tx.setText(log);
				
				isGPSTaskRunning = false;
				isGPSError = true;
				
				if(isAPNSuccess){
					closeProgressDialog();
					log += "\nGPS定位超时,APN成功, 转向APN定位结果";
					tx.setText(log);
					
					//	TODO:	goto apn success, show map
					return;
				}
				else if(isAPNError) {
					closeProgressDialog();
					log += "\nGPS定位超时,APN失败, 显示定位失败";
					tx.setText(log);
					Utils.Toast(getApplicationContext(), "定位失败,请重试");
					return;
				}
				break;				
			}
		}		
	}
	//	*******************************************************************************************
	private ProgressDialog progressdialog;
	private Timer timer;	
	private TimerTask mTimerTask;
	
	private void showProgressDialog(Context context, String title, String message, int TIME_OUT){
		if(progressdialog!=null)
			progressdialog.dismiss();
		
		progressdialog = ProgressDialog.show(context, title, message);

		progressdialog.setOnKeyListener(mProgressDialog_KeyListener);

		if(timer!=null)
			timer.cancel();
		timer = new Timer();

		if(mTimerTask != null)
			mTimerTask.cancel();
		mTimerTask = new TimerTask(){
			@Override
			public void run() {
				if(progressdialog!=null)
					progressdialog.dismiss();
				handler.sendEmptyMessage(2);
				return;
			}
		};
		timer.schedule(mTimerTask, TIME_OUT);
	}
	private void closeProgressDialog(){
		if(progressdialog!=null)
			progressdialog.dismiss();
	}
	OnKeyListener mProgressDialog_KeyListener = new ProgressDialog.OnKeyListener(){
		@Override
		public boolean onKey(DialogInterface dialog, int keyCode,
				KeyEvent event) {
			switch(keyCode){
			case KeyEvent.KEYCODE_BACK:
				dialog.dismiss();
				return true;
			}
			return false;
		}					
	};
}